/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Properties;

/**
 * <p>Project: spring2021 - AppConfig
 * <p>Powered by webrx On 2021-11-02 20:35:13
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration
@PropertySource("db.properties")
@MapperScan(basePackages = "cn.webrx.mapper", sqlSessionFactoryRef = "sf")
@ComponentScan(basePackages = {"cn.webrx.mapper", "cn.webrx.pojo"})
public class AppConfig {
    @Value("${db.url}")
    private String url;

    //读取外配置文件方法一
    @Value("${db.username}")
    private String username;


    //读取外配置文件方法二
    @Autowired
    private Environment env;


    @Bean(name = "ds", initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() {
        var ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setDriverClassName(env.getProperty("db.driver", "com.mysql.cj.jdbc.Driver"));
        return ds;
    }

    @Bean
    public SqlSessionFactoryBean sf(DruidDataSource ds) {
        var sf = new SqlSessionFactoryBean();
        //设置数据连接池
        sf.setDataSource(ds);

        //批量加载XxxMapper.xml映射文件
        var resolver = new PathMatchingResourcePatternResolver();
        try {
            sf.setMapperLocations(resolver.getResources("mapper/*Mapper.xml"));
        } catch (IOException ignored) {
        }

        //设置别名
        sf.setTypeAliasesPackage("cn.webrx.pojo,cn.webrx.vo");

        //注册分页插件
        var pi = new PageInterceptor();
        var prop = new Properties();
        prop.setProperty("reasonable", "true");
        pi.setProperties(prop);
        sf.setPlugins(pi);

        return sf;
    }
}
